import React, {useEffect, useState} from 'react'
import { Form, Button, DatePicker,Input, Modal, Row, Col,Popconfirm,Select,TreeSelect} from 'antd'
import { connect } from 'umi'
import moment from 'moment'
import {findItemByTree} from "@/utils/functions";
import {getDepartmentUser} from "@/pages/Personnel/Promotion/Management/service";

const FormItem = Form.Item
const {Option} = Select
const { RangePicker } = DatePicker;

const formLayout = {
  labelCol: { span: 7 },
}

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
}

const AddContractForm = (props) => {
  const { onSubmit, onCancel, loading,visible,currentUser,global = {} } = props
  const {options = {}} = global
  const {orgTree = [],jobLevel = []} = options
  const [unitTree, setUnitTree] = useState(orgTree)
  const [form] = Form.useForm()
  const [userList,setUserList] = useState([]);

  useEffect(() => {
    if(currentUser){
      const item = findItemByTree(orgTree, currentUser.orgId)
      setUnitTree([item])
    }
  }, [visible])

  const onFormCancel = () => {
    form.resetFields()
    onCancel()
  }

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields()
    form.resetFields()
    onSubmit({
      oid:fieldsValue.oid,
      contractStartTime:moment(fieldsValue.contractDate[0]).format('YYYY-MM-DD'),
      contractEndTime:moment(fieldsValue.contractDate[1]).format('YYYY-MM-DD')
    })
  }

  const selectDept = (value,node) =>{
    if(node.children.length < 1){
      getDepartmentUser(value).then((res) => {
        setUserList(res)
      })
    }
  }

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="selectDepartment" label="选择部门">
              <TreeSelect
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择部门"
                labelInValue={true}
                onSelect={(value,node) => selectDept(value,node)}
                treeData={unitTree}
              />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="oid" label="合同签订人" rules={[{required: true, message: '合同签订人不能为空'}]}>
              <Select placeholder="请选择合同签订人">
                { userList.length>0 ? userList.map((item, index) => {
                  return (
                    <Option value={`${item.oid}`} key={index}>
                      {item.name}
                    </Option>
                  )
                }) : ''}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="contractDate" label="合同起止日期" rules={[{required: true, message: '合同起止日期不能为空'}]}>
              <RangePicker className='widthStyle'/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Popconfirm title={`确认是否发送合同?`}
                    onConfirm={() => handleSubmit()}
                    okText="是"
                    cancelText="否">
          <Button type="primary" loading={loading}>提交</Button>
        </Popconfirm>
      </>
    )
  }

  return (
    <Modal
      width={1280}
      destroyOnClose
      title="新建合同"
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

export default connect(({global}) => ({
  global
}))(AddContractForm)
